package com.example.mapinformationandroid.UI;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.util.ArrayMap;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps2d.AMap;
import com.amap.api.maps2d.MapView;
import com.amap.api.maps2d.UiSettings;
import com.amap.api.maps2d.model.BitmapDescriptor;
import com.amap.api.maps2d.model.BitmapDescriptorFactory;
import com.amap.api.maps2d.model.LatLng;
import com.amap.api.maps2d.model.Marker;
import com.amap.api.maps2d.model.MarkerOptions;
import com.amap.api.maps2d.model.MyLocationStyle;
import com.example.mapinformationandroid.Adapter.InformationCardAdapter;
import com.example.mapinformationandroid.ConstantData.Define;
import com.example.mapinformationandroid.Http.HTTPBase;
import com.example.mapinformationandroid.MainActivity;
import com.example.mapinformationandroid.Model.Information;
import com.example.mapinformationandroid.Model.ResponseBase;
import com.example.mapinformationandroid.R;
import com.example.mapinformationandroid.Util.LocationUtils;
import com.linroid.filtermenu.library.FilterMenu;
import com.linroid.filtermenu.library.FilterMenuLayout;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;

public class Home extends AppCompatActivity implements View.OnClickListener {
    private FilterMenuLayout filterMenuLayout;
    private MapView mMapView = null;
    private String token;
    private AMap aMap;
    //x纬度 y经度
    private Double coordinate_x, coordinate_y;
    private SharedPreferences sharedPreferences;
    private String postcodes;
    private List<Information> informationList;
    private LocationUtils locationUtils;
    private RecyclerView recyclerView;
    private Map<Marker, Information> markerList;
    private InformationCardAdapter informationCardAdapter;
    private LinearLayoutManager linearLayoutManager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_home);
        mMapView = findViewById(R.id.map);
        //在activity执行onCreate时执行mMapView.onCreate(savedInstanceState)，创建地图
        mMapView.onCreate(savedInstanceState);
        initView();
        initData();
        startLocation();
    }

    @Override
    public void onClick(final View v) {
    }

    private void initView() {
        if (aMap == null) {
            aMap = mMapView.getMap();
        }

        //设置用户位置图标
        BitmapDescriptor bitmapDescriptor = BitmapDescriptorFactory.fromResource(R.drawable.user_maker_icon);
        MyLocationStyle myLocationStyle = new MyLocationStyle();
        myLocationStyle.myLocationType(MyLocationStyle.LOCATION_TYPE_LOCATE);
        myLocationStyle.myLocationIcon(bitmapDescriptor);
        //设置精度圈颜色
        myLocationStyle.strokeColor(Color.argb(0, 0, 0, 0));// 设置圆形的边框颜色
        myLocationStyle.radiusFillColor(Color.argb(0, 0, 0, 0));
        aMap.setMyLocationStyle(myLocationStyle);
        aMap.setMyLocationEnabled(true);

        //显示量尺与指南针
        UiSettings mUiSettings;//定义一个UiSettings对象
        mUiSettings = aMap.getUiSettings();
        mUiSettings.setScaleControlsEnabled(true);
        mUiSettings.setCompassEnabled(true);
        //设置缩放等级 为17
        recyclerView = findViewById(R.id.rc_information_card);
        linearLayoutManager = new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false);
        recyclerView.setLayoutManager(linearLayoutManager);
        filterMenuLayout = findViewById(R.id.fm_home);
        attachMenu(filterMenuLayout);
    }

    private void initData() {
        informationList = new ArrayList<>();
        postcodes = "";
        markerList = new ArrayMap<>();
        locationUtils = new LocationUtils(this, locationListener);
        sharedPreferences = getSharedPreferences("user", Activity.MODE_PRIVATE);
        token = sharedPreferences.getString(Define.UserDefine.USER_TOKEN, "");
    }


    /**
     * 定位监听
     */
    AMapLocationListener locationListener = new AMapLocationListener() {
        @Override
        public void onLocationChanged(AMapLocation location) {
            if (null != location) {

                StringBuffer sb = new StringBuffer();
                //errCode等于0代表定位成功，其他的为定位失败，具体的可以参照官网定位错误码说明
                if (location.getErrorCode() == 0) {
                    sb.append("定位成功" + "\n");
                    coordinate_y = location.getLongitude();
                    sb.append("经    度    : " + coordinate_y + "\n");
                    coordinate_x = location.getLatitude();
                    sb.append("纬    度    : " + coordinate_x + "\n");
                    sb.append("精    度    : " + location.getAccuracy() + "米" + "\n");
                    // 获取当前提供定位服务的卫星个数
                    sb.append("省            : " + location.getProvince() + "\n");
                    sb.append("市            : " + location.getCity() + "\n");
                    postcodes = location.getAdCode();
                    sb.append("城市编码 : " + location.getCityCode() + "\n");
                    sb.append("区            : " + location.getDistrict() + "\n");
                    sb.append("区域 码   : " + postcodes + "\n");
                    sb.append("地    址    : " + location.getAddress() + "\n");
                    //定位完成的时间
                } else {
                    //定位失败
                    sb.append("定位失败" + "\n");
                    sb.append("错误码:" + location.getErrorCode() + "\n");
                    sb.append("错误信息:" + location.getErrorInfo() + "\n");
                    sb.append("错误描述:" + location.getLocationDetail() + "\n");
                }
                sb.append("***定位质量报告***").append("\n");
                sb.append("* WIFI开关：").append(location.getLocationQualityReport().isWifiAble() ? "开启" : "关闭").append("\n");
                sb.append("* GPS星数：").append(location.getLocationQualityReport().getGPSSatellites()).append("\n");
                sb.append("* 网络类型：" + location.getLocationQualityReport().getNetworkType()).append("\n");
                sb.append("* 网络耗时：" + location.getLocationQualityReport().getNetUseTime()).append("\n");
                sb.append("****************").append("\n");
                //定位之后的回调时间
                //解析定位结果，
                String result = sb.toString();
                Log.d("Home", result);
                setInformationInMap();
            } else {
                Toast.makeText(Home.this, "定位失败", Toast.LENGTH_SHORT).show();
            }
        }
    };

    private FilterMenu attachMenu(FilterMenuLayout layout) {
        return new FilterMenu.Builder(this)
                .addItem(R.drawable.refresh_location)
                .addItem(R.drawable.refresh_map)
                .addItem(R.drawable.add_information)
                .addItem(R.drawable.personal_home)
                .attach(layout)
                .withListener(listener)
                .build();
    }

    FilterMenu.OnMenuChangeListener listener = new FilterMenu.OnMenuChangeListener() {
        @Override
        public void onMenuItemClick(View view, int position) {
            switch (position) {
                case 0:
                    Toast.makeText(Home.this, "定位中", Toast.LENGTH_SHORT).show();
                    startLocation();
                    break;
                case 1:
                    Toast.makeText(Home.this, "刷新资讯", Toast.LENGTH_SHORT).show();
                    if (!postcodes.isEmpty()) {
                        //判断是否登录
                        if (!token.isEmpty()) {
                            getInformation(Integer.parseInt(postcodes), token);
                        } else {
                            sharedPreferences.edit().clear().commit();
                            startActivity(new Intent(Home.this, Login.class));
                            finish();
                        }
                    } else {
                        Toast.makeText(Home.this, "请打开定位", Toast.LENGTH_SHORT).show();
                    }
                    break;
                case 2:
                    startActivity(new Intent(Home.this,AddInformation.class));
                    break;
                case 3:
                    startActivity(new Intent(Home.this,PersionHome.class));
            }
        }

        @Override
        public void onMenuCollapse() {

        }

        @Override
        public void onMenuExpand() {

        }
    };

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mMapView.onDestroy();
        locationUtils.destroyLocation();

    }

    @Override
    protected void onResume() {
        super.onResume();
        mMapView.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        mMapView.onPause();
    }

    //显示资讯点
    private void setMapPoint(List<Information> informationList) {
        BitmapDescriptor bitmapDescriptor = BitmapDescriptorFactory.fromResource(R.drawable.infromation_message_icon);
        for (Information information : informationList) {

            MarkerOptions markerOption = new MarkerOptions();
            markerOption.position(new LatLng(Double.parseDouble(information.getCoordinate_x()), Double.parseDouble(information.getCoordinate_y())));
            markerOption.title(information.getTitle()).snippet(information.getPlace());
            markerOption.draggable(false);//设置Marker可拖动
            markerOption.icon(bitmapDescriptor);
            Marker marker = aMap.addMarker(markerOption);
            marker.setObject(information);
            markerList.put(marker,information);

        }

        AMap.OnMarkerClickListener markerClickListener = new AMap.OnMarkerClickListener() {
            // marker 对象被点击时回调的接口
            // 返回 true 则表示接口已响应事件，否则返回false
            @Override
            public boolean onMarkerClick(Marker marker) {
                if (marker.getObject() instanceof Information) {
                    Information information = (Information) marker.getObject();
                    marker.showInfoWindow();
                    recyclerView.scrollToPosition(Integer.parseInt(marker.getId())-1);
                    Toast.makeText(Home.this, "这是"+information.getTitle(), Toast.LENGTH_SHORT).show();
                }
                return false;
            }
        };
// 绑定 Marker 被点击事件
        aMap.setOnMarkerClickListener(markerClickListener);
    }

    @Override
    protected void onSaveInstanceState(@NonNull Bundle outState) {
        super.onSaveInstanceState(outState);
        mMapView.onSaveInstanceState(outState);
    }

    //获取定位
    protected void startLocation() {
        if (ContextCompat.checkSelfPermission(Home.this, Manifest.permission.ACCESS_FINE_LOCATION)
                != PackageManager.PERMISSION_GRANTED) {//未开启定位权限
            //开启定位权限,200是标识码
            ActivityCompat.requestPermissions(Home.this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 200);
        }
        Toast.makeText(Home.this, "正在定位", Toast.LENGTH_SHORT).show();

        locationUtils.startLocation(aMap);
    }

    //拉取数据
    protected void getInformation(int postcodes, final String token) {
        HTTPBase httpBase = new HTTPBase();
        httpBase.getInformationListByPost(postcodes, token, new Observer<ResponseBase<List<Information>>>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(ResponseBase<List<Information>> value) {
                //判断token如果过期就重新登录
                if (value.getCode() == Define.HttpDefine.TOKEN_INVALID) {
                    sharedPreferences.edit().clear().commit();
                    startActivity(new Intent(Home.this, Login.class));
                    finish();
                } else {
                    if (value.getCode() == Define.HttpDefine.HTTP_SUCCESS) {
                        informationList = value.getData();
                        Toast.makeText(Home.this, "请求成功", Toast.LENGTH_SHORT).show();
                        setMapPoint(informationList);
                        informationCardAdapter = new InformationCardAdapter(informationList, Home.this);
                        recyclerView.setAdapter(informationCardAdapter);
                    } else {
                        Toast.makeText(Home.this, Define.HttpDefine.HTTP_ERROR_MSG, Toast.LENGTH_SHORT).show();

                    }
                }
            }

            @Override
            public void onError(Throwable e) {
                Log.d("Home", Define.HttpDefine.HTTP_ERROR_MSG);
            }

            @Override
            public void onComplete() {

            }
        });
    }
    //把资讯显示在地图上
    protected void setInformationInMap() {


        if (!postcodes.isEmpty()) {
            //判断是否登录
            if (!token.isEmpty()) {
                getInformation(Integer.parseInt(postcodes), token);
            } else {
                sharedPreferences.edit().clear().apply();
                startActivity(new Intent(Home.this, Login.class));
                finish();
            }
        } else {
            Toast.makeText(Home.this, "请打开定位", Toast.LENGTH_SHORT).show();
        }
    }

    //权限申请回调
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case 200://刚才的识别码
                if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {//用户同意权限,执行我们的操作
                    Toast.makeText(Home.this, "正在定位", Toast.LENGTH_SHORT).show();
                    locationUtils.startLocation(aMap);
                } else {//用户拒绝之后,当然我们也可以弹出一个窗口,直接跳转到系统设置页面
                    Toast.makeText(Home.this, "未开启定位权限,请手动到设置去开启权限", Toast.LENGTH_LONG).show();
                }
                break;
            default:
                break;
        }

    }
}


